import { Routes } from '@vue/router/routes'
import {
  addActiveMenu,
  getMenuMap,
  getToken,
  includeActiveMenus,
  includeMenusMap,
  setActiveMenu
} from '@/util/store'
import Vue from 'vue'
import VueRouter from 'vue-router'
import Admin from './mod/admin'
import _import from './_import'

const Pages = _import('web/pages')
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: Routes.Login,
    alias: '/login',
    component: Pages('admin-login/Index')
  },
  {
    path: '/admin',
    name: Routes.Admin,
    component: Pages('admin/Index'),
    redirect: { name: Routes.Home },
    children: Admin
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeResolve(({ name }, from, next) => {
  const isLogin = name === Routes.Login
  const token = getToken()
  if (isLogin) {
    token ? next(Routes.Admin) : next()
  } else {
    if (token) {
      if (includeMenusMap(name)) {
        includeActiveMenus(name) || addActiveMenu(getMenuMap(name))
        setActiveMenu(name)
        next()
      } else {
        next(false)
      }
    } else {
      next(Routes.Login)
    }
  }
})

export default router
